package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/v1/file/upload")
public class UploadController {

    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        log.debug("开始处理【文件上传】的请求，参数：{}", filename);
        //获取扩展名
        String extName = filename.substring(filename.lastIndexOf("."));
        //生成UUID
        filename = UUID.randomUUID()+extName;
        log.debug("保存的文件名：{}", filename);
        //处理日期路径
        String dirPath = "D:/files";
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        File file1 = new File(dirPath+datePath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        log.debug("保存文件的目录：{}", file1.getAbsolutePath());
        file.transferTo(new File(file1, filename));
        return JsonResult.ok(datePath+filename);
    }

}
